<template>
	<view class="contain padding-12">
		<view class="f-w-500"> 请补充以下问题，以便更准确的了解您的身体状况，提升分析结果的准确性。</view>
		
		<view :key="index" class="padding-12 bg-shadow-0 margin-t12 b-radius-5">
			<view class="f-w-500">请勾选你有以下哪些症状</view>
			<view @click="choose(index)" v-for="(item,index) in list" :key="index" class="flex f-a-c margin-t12">
				<view v-if="item.isChoose" class="flex f-a-c van-icon van-icon-checked t-color-g f20-size margin-r12"></view>
				<view v-else class="flex f-a-c van-icon van-icon-circle t-color-e3 f20-size margin-r12"></view>
				<view>{{item.name}}</view>
			</view>
		</view>
		
		<view @click="pay">
			<b-button text="下一步"></b-button>
		</view>
	</view>
</template>
<style scoped>
/* @import '@/static/css/index/index.css'; */
</style>
<script>
	const $ = require('@/utils/api.js');
	let self = this;
	export default {
		components: {},
		data() {
			return {
				list: [],
				id: ''
			};
		},
		onLoad: function(options) {
			self = this;
			this.id = options.id ? options.id : '';
			if(this.id == '') {
				this.id = uni.getStorageSync('qsData') ?uni.getStorageSync('qsData').session_id : ''
			}
			this.init();
		},
		onShow() {
		},
		methods: {
			showPay(id) {
				const self = this;
				tt.getOrderPayment({
					orderId: id,
					success: (res) => {
						self.next();
					},
					complete: (res) => {
						console.log(res,'errr')
					}
				})
			},
			pay() {
				const self = this;
				// #ifdef H5
				self.next();
				return;
				// #endif
				// $.ajax({
				// 	url: 'bingdouyanzhidypay/index/requestOrder',
				// 	data: {},
				// 	method: 'POST',
				// 	success(res) {
				// 		tt.requestOrder({
				// 		    data: res.data, // 请勿在前端对data做任何处理
				// 		    byteAuthorization: res.byteAuthorization, // 请勿在前端对byteAuthorization做任何处理
				// 		    success: (res) => {
				// 		      console.log('成功', res);
				// 			  self.showPay(res.orderId);
				// 		    },
				// 		    fail: (res) => {
				// 		      console.log(res)
				// 		    },
				// 		  });
						
				// 	}
				// })
			},
			next() {
				const arr = this.list.filter(ele => ele.isChoose).map((ele) =>{
					delete ele.isChoose
					return ele
				});
				const postData = {
					session_id: this.id,
					answers: JSON.stringify(arr),
				}
				uni.setStorageSync('qsData',postData);
				// uni.setStorageSync('qsData',answers);
				this.rechargeMembership(JSON.stringify(arr));
				//this.go('/pages/index/report');
			},
			choose(index) {
				let info = this.list[index];
				if(info.isChoose) {
					info.isChoose = false;
				}else{
					info.isChoose = true;
				}
				this.$set(this.list,index,info);
			},
			init() {
				this.list = uni.getStorageSync('qs') ? uni.getStorageSync('qs') : [];
			},
			async rechargeMembership(answer) {
			  // 请求服务端获取微信支付参数
			  try {
			    const response = await fetch('https://data.bingdou.site/server/oneyuan/index/pay', {
			      method: 'POST',
			      headers: {
			        'Content-Type': 'application/json'
			      },
			      body: JSON.stringify({
			        open_id: localStorage.getItem('openid'),
					type: 4,
					session_id: this.id,
					answer: answer
			      })
			    });
			    const data = await response.json();
				this.orderNo = data.data.order_no;
				  
				if (typeof WeixinJSBridge == "undefined") {
					  if (document.addEventListener) {
						  document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
					  } else if (document.attachEvent) {
						  document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
						  document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
					  }
				  } else {
					  this.onBridgeReady(data);
				  }
				} catch (error) {
				  console.error('请求支付参数时出错:', error);
				}
			},
			
			onBridgeReady(data) {
					  var that = this
					  WeixinJSBridge.invoke('getBrandWCPayRequest', {
					      "appId": data.data.appId,     //公众号ID，由商户传入     
					      "timeStamp": data.data.timeStamp,     //时间戳，自1970年以来的秒数     
					      "nonceStr": data.data.nonceStr,      //随机串     
					      "package": data.data.package,
					      "signType": "MD5",     //微信签名方式：     
					      "paySign": data.data.paySign,
					  },
					  function(res) {
					      if (res.err_msg == "get_brand_wcpay_request:ok") {
					          // 使用以上方式判断前端返回,微信团队郑重提示：
					          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
					  		  that.pollPaymentResult();
					      }
					  });
			},
			async pollPaymentResult() {
			  const pollInterval = 1000; // 轮询间隔时间（毫秒）
			  const maxAttempts = 20; // 最大轮询次数
			  let attempts = 0;
					const orderNo = this.orderNo;
			  const poll = async () => {
			    try {
			      const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/getOrderPayment?order_no=${orderNo}`);
			      const data = await response.json();
			      if (data.code === 0) {
			        // 支付成功
			        // alert('充值成功');
			        // this.getAvailableTimes(localStorage.getItem('openid')); // 更新会员信息
					window.location.href=""
			        return;
			      } else if (data.code === 1) {
			        // 支付进行中，继续轮询
			        if (attempts < maxAttempts) {
			          attempts++;
			          setTimeout(poll, pollInterval);
			        } else {
			          alert('支付结果查询超时');
			        }
			      } else {
			        // 支付失败
			        alert('支付失败');
			      }
			    } catch (error) {
			      console.error('查询支付结果时出错:', error);
			      alert('查询支付结果时出错');
			    }
			  };
			
			  poll();
			}
		},
		computed: {},
		created() {
		},
		mounted() {},
		destroyed() {},
		onPullDownRefresh() {
		},
		onReachBottom() {
			
		}
	}
</script>